import struct
from types import IntType
#import serial

def strToHex(s):
    return "".join(["\\x%02X" % ord(i) for i in s])

def crc16str(s):
    crc = 0
    for index1 in range(len(s)):
        if type(s[index1]) is IntType:
            x = s[index1]
        else:
            x = ord(s[index1])
        crc = crc ^ x << 8
        for index2 in range(1, 9):
            if crc & 0x8000 != 0:
                crc = (((crc << 1) ^ 0x1021)) & 0xffff
            else:
                crc = (crc << 1) & 0xffff
        #print crc & 0xFFFF
    return crc & 0xFFFF

def sendMessage(msg):
    result ='\x44\x00\x00\xff\xff\x00\x00'+ chr(len(msg))+'\x00\x89'+msg
    crc=crc16str(result)
    result += struct.pack('H',crc)
    print strToHex(result)
    result = result.replace('\x7d','\x7d\x5d').replace('\x7e','\x7d\x5e')
    result = '\x7e' + result + '\x7e'
    #return result
    print len(result)
    return strToHex(result)

print (sendMessage('\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02'))
#print (sendMessage('\x70\x01\x01\x00\x17\x32\x33\x34\x35'))
'''
ss = serial.Serial('/dev/ttySAC2', 115200)
ss.open()
if ss.isOpen() :
	print 'Open success'
	ss.write(sendMessage('\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02'))
'''
#print (sendMessage('\x02\x00\x01\x00\x01\x00\x00'))
